package com.study.ceph.connection;

import com.amazonaws.services.s3.AmazonS3;
import com.study.ceph.config.CephConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.DestroyMode;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

@Slf4j
public class CephConnectionFactory extends BasePooledObjectFactory<AmazonS3> {

    private CephConfig cephConfig;

    public CephConnectionFactory(CephConfig cephConfig) {
        this.cephConfig = cephConfig;
    }

    /**
     * 创建连接对象
     *
     * @return
     * @throws Exception
     */
    @Override
    public AmazonS3 create() throws Exception {
        return CephUtil.getConnection(cephConfig.getAccessKey(), cephConfig.getSecretKey(), cephConfig.getEndpoint(),
                cephConfig.getSigner(), cephConfig.getSigning());
    }

    @Override
    public PooledObject<AmazonS3> wrap(AmazonS3 obj) {
        return new DefaultPooledObject<>(obj);
    }

    /**
     * 校验连接是否可用
     *
     * @param p
     * @return
     */
    @Override
    public boolean validateObject(PooledObject<AmazonS3> p) {
        try {
            p.getObject().listBuckets();
            log.info("连接验证通过：{}", Thread.currentThread().getName());
        } catch (Exception e) {
            log.error("连接已失效：{}", e);
            return false;
        }
        return true;
    }

    /**
     * 销毁连接对象
     *
     * @param p
     * @param mode
     * @throws Exception
     */
    @Override
    public void destroyObject(PooledObject<AmazonS3> p, DestroyMode mode) throws Exception {
        if (null != p) {
            p.getObject().shutdown();
        }

    }

}
